package org.duiduo.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.duiduo.constant.BaseConstant;
import org.duiduo.constant.ResponseConstants;
import org.duiduo.pojo.TbUser;
import org.duiduo.repository.TbUserMapper;
import org.duiduo.result.ResultData;
import org.duiduo.service.TbUserService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * Service层
 *
 * @author 夜泷noga
 */
@Slf4j
@Service(value = "TbUserServiceImpl")
public class TbUserServiceImpl implements TbUserService {

    @Value("${spring.mail.username}")
    private String mailFrom;

    // @Autowired
    // private TbUserRepository repository;

    @Autowired
    private TbUserMapper userMapper;

    @Resource
    private Redisson redisson;

    @Autowired
    private JavaMailSender sender;

    @Override
    public List<TbUser> getList(String username) {
        // TODO Auto-generated method stub
        // TbUser user = TbUser.builder()
        // .username(username)
        // .build();
        // ExampleMatcher matcher = ExampleMatcher.matching()
        // .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains());
        // Example<TbUser> example = Example.of(user, matcher);
        // repository.findAll(example);
        Example example = new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("username", "%" + username + "%");
        return userMapper.selectByExample(example);
    }

    @Override
    public void delete(Integer id) {
        // TODO Auto-generated method stub
        // repository.deleteById(id);
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ResultData addOrEdit(TbUser user) {
        // TODO Auto-generated method stub
        String lockName = BaseConstant.TB_USER_ADD_EDIT_LOCK;
        // 锁
        RLock lock = null;
        try {
            lock = redisson.getLock(lockName);
            if (lock.tryLock()) {
                // 睡眠1分钟
                // Thread.sleep(600000);
                // 保存
                // repository.saveAndFlush(user);
                if (user.getId() == null) {
                    // 添加
                    userMapper.insertSelective(user);
                } else {
                    // 修改
                    userMapper.updateByPrimaryKeySelective(user);
                }
                return ResultData.success();
            }
            return ResultData.error(ResponseConstants.Resp.RESP_02.getCode(),
                    ResponseConstants.Resp.RESP_02.getMessage());
        } catch (Exception e) {
            log.error("异常:", e);
            return ResultData.error(ResponseConstants.Resp.RESP_01.getCode(),
                    ResponseConstants.Resp.RESP_01.getMessage());
        } finally {
            // 释放锁
            if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    public TbUser findById(Integer id) {
        // TODO Auto-generated method stub
        // repository.findById(id).get();
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public TbUser getByUsernameAndPassword(String username, String password) {
        // TbUser user = TbUser.builder()
        // .username(username)
        // .password(password)
        // .build();
        // Example<TbUser> example = Example.of(user);
        // List<TbUser> all = repository.findAll(example);

        Example example = new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username).andEqualTo("password", password);
        List<TbUser> all = userMapper.selectByExample(example);
        return CollectionUtils.isEmpty(all) ? null : all.get(0);
    }

    @Override
    public void sendMail(SimpleMailMessage message) {
        message.setFrom(mailFrom);
        sender.send(message);
    }
}
